package com.ziroom.finance.rabbitmq.common.util;

import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * copied from financialCenter
 * used for generating html
 */
public class HtmlGenerator {     
         
    /**   
     * Generate html string.   
     *    
     * @param template   classpath 中模板路径.   
     * @param variables  模板参数.   
     * @return htmlStr   
     * @throws IOException 
     * @throws TemplateException 
     * @throws Exception   
     */    
    public static String generate(String template, Map<String,Object> variables) throws IOException, TemplateException{     
        BufferedWriter writer = null;   
        String htmlContent = "";
        try{
        	Configuration config = FreemarkerConfiguration.getConfiguation();
//            config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); //忽略异常
        	Template tp = config.getTemplate(template,"UTF-8");     
        	StringWriter stringWriter = new StringWriter();       
        	writer = new BufferedWriter(stringWriter);  
        	
        	tp.setEncoding("UTF-8");       
        	tp.process(variables, writer);       
        	htmlContent = stringWriter.toString();     
        	writer.flush();       
        	
        }finally{
        	if(writer!=null)
        		writer.close();     
        }
        return htmlContent;     
    }     
    
    public static void main(String[] args) throws Exception {
        Map<String,Object> param = Maps.newHashMap();
        param.put("loanRate",111);
        try {
            String html = HtmlGenerator.generate("template/loanyuan.html",param);
            HtmltoPDF.htmlStrToPdf(html, "d:/tmp/templete.pdf");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} 
